package cn.wwcyc.controller;

import cn.wwcyc.dao.ModbusDao;
import cn.wwcyc.domain.*;
import cn.wwcyc.exception.WWExceptionEnum;
import cn.wwcyc.mapper.TDjxxMapper;
import cn.wwcyc.service.*;
import cn.wwcyc.utils.JWTUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.serotonin.modbus4j.exception.ErrorResponseException;
import com.serotonin.modbus4j.exception.ModbusInitException;
import com.serotonin.modbus4j.exception.ModbusTransportException;

import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/dj")

public class DJController {

    //    @Autowired
//    UserService userService;
    @Autowired
    TDjxxMapper djxxMapper;
    @Autowired
    TDjxxService djxxService;
    @Autowired
    TjDwService tjDwService;
    @Autowired
    TjGxService gxService;
    @Autowired
    TjLogService logService;

    //此分页函数中的返回对象中不含有单位及干线对象数据
    @RequestMapping("/getpage1")
    public R<IPage<TDjxx>> getPage(
            @RequestParam Integer pagenum,
            @RequestParam Integer pagesize,
            @RequestParam(required = false) String jh,
            @RequestParam(required = false) Long dw
    ) {
        LambdaQueryWrapper<TDjxx> qw = new LambdaQueryWrapper();
        if (!StringUtils.isBlank(jh))
            qw.like(TDjxx::getJh, jh);
        IPage<TDjxx> page = new Page<>(pagenum, pagesize);
        page = djxxMapper.selectPage(page, qw);
        return R.success(page);
    }

    //此分页函数中的返回对象中含有单位及干线对象数据
    @RequestMapping("/getpage")
    public R<IPage<TDjxx>> getPage(
            @RequestParam Integer pagenum,
            @RequestParam Integer pagesize,
            @RequestParam(required = false) String jh
    ) {
        IPage<TDjxx> page = new Page<>(pagenum, pagesize);
        QueryWrapper<TDjxx> qw = new QueryWrapper<>();
        if (!StringUtils.isBlank(jh)) {
            qw.like("jh", jh);
        }

        long count = djxxMapper.selectCount(qw);

        page.setTotal(count);
        page.setPages(page.getTotal() % page.getSize() == 0 ? page.getTotal() / page.getSize() : page.getTotal() / page.getSize() + 1);
        if (pagenum > page.getPages()) {
            page.setCurrent(page.getPages());
        }
        if (pagenum < 1) {
            page.setCurrent(1);
        }
        System.out.println("pagenum:" + pagenum + "  pagesize:" + pagesize + " current:" + page.getCurrent() + "  size:" + page.getSize() + " pages:" + page.getPages());
        List<TDjxx> list = djxxMapper.selectPagewithdwgx(page.getCurrent(), page.getSize(), jh);
        page.setRecords(list);
        return R.success(page);
    }


    @RequestMapping("/getpageBydwgxjh")
    public R<IPage<TDjxx>> getPageBydwgxjh(
            @RequestParam Integer pagenum,
            @RequestParam Integer pagesize,
            @RequestParam(required = false) String jh,
            @RequestParam(required = false) Long dw,
            @RequestParam(required = false) Long gx
    ) {
        IPage<TDjxx> page = new Page<>(pagenum, pagesize);
        QueryWrapper<TDjxx> qw = new QueryWrapper<>();
        if (!StringUtils.isBlank(jh)) {
            qw.like("jh", jh);
        }

        TjDw tjDw = null;
        if (dw != null) {
            tjDw = tjDwService.getDwTreeById(dw);
        }
        List<TjDw> dwlist = new ArrayList<>();
        dwlist = tjDwService.DwTreeToList(dwlist, tjDw);
        List<Long> dwIdList = new ArrayList<>();
        for (TjDw tjDw1 : dwlist) {
            dwIdList.add(tjDw1.getId());
        }
        if( gx != null){
            qw.eq("gx",gx);
        }
        if( dwIdList.size()>0){
            qw.in("dw",dwIdList);
        }
        long count = djxxMapper.selectCount(qw);
        page.setTotal(count);
        page.setPages(page.getTotal() % page.getSize() == 0 ? page.getTotal() / page.getSize() : page.getTotal() / page.getSize() + 1);
        if (pagenum > page.getPages()) {
            page.setCurrent(page.getPages());
        }
        if (pagenum < 1) {
            page.setCurrent(1);
        }
        System.out.println("pagenum:" + pagenum + "  pagesize:" + pagesize + " current:" + page.getCurrent() + "  size:" + page.getSize() + " pages:" + page.getPages());
        List<TDjxx> list = djxxMapper.selectPagewithdwgxBydwgxjh(page.getCurrent(), page.getSize(), jh, dwIdList, gx);
        page.setRecords(list);
        return R.success(page);
    }


    @GetMapping("/test")
    public R<List<TDjxx>> test(
            @RequestParam(required = false) String jh,
            @RequestParam(required = false) Long dw,
            @RequestParam(required = false) Long gx
    ) {
        djxxMapper.selectTjDjxxList();
        return R.success();
    }

    @GetMapping("/getlist")
    public R<List<TDjxx>> getList(
            @RequestParam(required = false) String jh,
            @RequestParam(required = false) Long dw,
            @RequestParam(required = false) Long gx
    ) {
        System.out.println("--------dw:" + dw);
        System.out.println("--------jh:" + jh);
        System.out.println("--------gx:" + gx);
        TjDw tjDw = null;
        if (dw != null) {
            tjDw = tjDwService.getDwTreeById(dw);
        }
        List<TjDw> dwlist = new ArrayList<>();
        dwlist = tjDwService.DwTreeToList(dwlist, tjDw);
        List<Long> dwIdList = new ArrayList<>();
        for (TjDw tjDw1 : dwlist) {
            dwIdList.add(tjDw1.getId());
        }
        List<TDjxx> list = djxxService.listTDjxx(jh, dwIdList, gx);
        return R.success(list);
    }

    @GetMapping("/getById")
    public R<TDjxx> getList(
            @RequestParam(required = false) Long id
    ) {
        TDjxx tDjxx = djxxService.getById(id);
        return R.success(tDjxx);
    }

    //单个抽油机停机
    @PostMapping("/tj")
    public R CyjTj(HttpServletRequest request, @RequestBody TDjxx tDjxx) {
        User user = JWTUtil.getCurrentUser();
        String ip = getIp(request);
        TjLog oplog = new TjLog();
        oplog.setUsername(user.getUsername());
        oplog.setIp(ip);
        oplog.setOptype("单井停机");
        oplog.setCreatedate(new Date());
        try {
            ModbusDao.setCoilStatus(tDjxx.getIp(), 1, 10007, true);
        } catch (ModbusInitException e1) {
            String opcontent = tDjxx.getJh()+ "井停机失败，错误："+e1.getMessage() ;
            oplog.setOpcontent(opcontent);
            logService.save(oplog);
            return R.error(WWExceptionEnum.Modbus_ERROR);
        } catch (ModbusTransportException e2) {
            String opcontent = tDjxx.getJh()+ "井停机失败，错误："+e2.getMessage() ;
            oplog.setOpcontent(opcontent);
            logService.save(oplog);
            return R.error(WWExceptionEnum.Modbus_ERROR);
        } catch (ErrorResponseException e3) {
            String opcontent = tDjxx.getJh()+ "井停机失败，错误："+e3.getMessage() ;
            oplog.setOpcontent(opcontent);
            logService.save(oplog);
            return R.error(WWExceptionEnum.Modbus_ERROR);
        } catch (Exception e) {
            String opcontent = tDjxx.getJh()+ "井停机失败，错误："+e.getMessage() ;
            oplog.setOpcontent(opcontent);
            logService.save(oplog);
            return R.error(WWExceptionEnum.SYSTEM_ERROR);
        }
        String opcontent = tDjxx.getJh()+ "井停机成功" ;
        oplog.setOpcontent(opcontent);
        logService.save(oplog);
        return R.success();
    }

    private String getIp(HttpServletRequest request) {
        String ip = null;
        if (request.getHeader("x-forwarded-for") == null) {
            ip = request.getRemoteAddr();
        } else {
            String xff = request.getHeader("x-forwarded-for");
            if (xff != null && xff.length() != 0) {
                ip = xff.split(",")[0];
            }
        }
        return ip;
    }

    @PostMapping("/batchtj")
    public R<List<TDjxx>> CyjTj(HttpServletRequest request, @RequestBody List<TDjxx> tDjxxList) {
//        System.out.println(tDjxxList);
        User user = JWTUtil.getCurrentUser();
        String ip = getIp(request);
//        System.out.println("--------------"+request.getRemoteHost());
//        System.out.println("--------------"+request.getRemoteAddr());
//        System.out.println(tDjxxList);
        List<TDjxx> errDjList = new ArrayList<>();
        for (TDjxx tDjxx : tDjxxList) {
            try {
                ModbusDao.setCoilStatus(tDjxx.getIp(), 1, 10007, true);
            } catch (ModbusInitException e1) {
                errDjList.add(tDjxx);
//                return R.error(WWExceptionEnum.Modbus_ERROR);
            } catch (ModbusTransportException e2) {
                errDjList.add(tDjxx);
//                return R.error(WWExceptionEnum.Modbus_ERROR);
            } catch (ErrorResponseException e3) {
                errDjList.add(tDjxx);
//                return R.error(WWExceptionEnum.Modbus_ERROR);
            } catch (Exception e) {
                errDjList.add(tDjxx);
//                return R.error(WWExceptionEnum.SYSTEM_ERROR);
            }
        }

        if (errDjList.size() == 0) {
            TjLog oplog = new TjLog();
            oplog.setUsername(user.getUsername());
            oplog.setIp(ip);
            oplog.setOptype("批量停机");
            String opcontent = "批量停机" + tDjxxList.size() + "个抽油机，成功" + tDjxxList.size() + "个; 成功井号：";
            for (TDjxx tDjxx : tDjxxList) {
                opcontent += tDjxx.getJh() + ", ";
            }
            opcontent = opcontent.substring(0, opcontent.length() - 2);
            oplog.setOpcontent(opcontent);
            oplog.setCreatedate(new Date());
            logService.save(oplog);
            return R.success();
        } else {
            TjLog oplog = new TjLog();
            oplog.setUsername(user.getUsername());
            oplog.setIp(ip);
            oplog.setOptype("批量停机");
            String opcontent = "批量停机" + tDjxxList.size() + "个抽油机，" +
                    "成功" + (tDjxxList.size() - errDjList.size()) + "个; "
                    + "失败" + errDjList.size() + "个; ";
            if (tDjxxList.size() - errDjList.size() > 0) {
                opcontent += "成功井号：";
                for (TDjxx tDjxx : tDjxxList) {
                    if (!errDjList.contains(tDjxx)) {
                        opcontent += tDjxx.getJh() + ", ";
                    }
                }
                opcontent = opcontent.substring(0, opcontent.length() - 2);
            }
            if (errDjList.size() > 0) {
                opcontent += "; 失败井号：";
                for (TDjxx tDjxx : tDjxxList) {
                    if (errDjList.contains(tDjxx)) {
                        opcontent += tDjxx.getJh() + ", ";
                    }
                }
                opcontent = opcontent.substring(0, opcontent.length() - 2);
            }

            oplog.setOpcontent(opcontent);
            oplog.setCreatedate(new Date());
            logService.save(oplog);

            String msg = "批量停机错误！井号：";
            for (TDjxx tDjxx : errDjList) {
                msg += tDjxx.getJh() + ", ";
            }
            msg = msg.substring(0, msg.length() - 2);
            return R.error(22002, msg);
        }
    }

//
//    @GetMapping("/getpage")
//    public R<IPage<User>> getpage(@RequestParam Integer pagenum, @RequestParam Integer pagesize){
//        IPage<User> page = new Page<>(pagenum, pagesize);
//        page = userService.page(page);
//
//        return R.success(page);
//    }

    @PostMapping("/save")
    public R save(@RequestBody TDjxx dj) {
        djxxService.save(dj);
        return R.success();
    }

    @PostMapping("/edit")
    public R edit(@RequestBody TDjxx dj) {
//        System.out.println(user);
        //原始的update不能处理roleid为空的情况！，这里自己写一个
        djxxService.updateById(dj);
        return R.success();
    }

    //
    @DeleteMapping
    public R del(Integer id) {
        djxxService.removeById(id);
        return R.success();
    }

    @PostMapping("delbatch")
    public R delbatch(@RequestBody List<TDjxx> tDjxxList) {
        for (TDjxx dj : tDjxxList) {
            Long id = dj.getId();
            djxxService.removeById(id);
        }
        return R.success();
    }


//
//    @GetMapping("/getpage1")
//    public R<IPage<UserRoleMenuVo>> getpage1(@RequestParam Integer pagenum, @RequestParam Integer pagesize, @RequestParam(required=false) String username){
//
//        IPage<UserRoleMenuVo> page = new Page<>(pagenum, pagesize);
//        page = userService.getUserRoleMenuVo(page,  username);
//        return R.success(page);
//    }

    //批量导入单井数据
    @PostMapping("/import")
    public R batchImport(@RequestParam MultipartFile file) throws IOException {
        System.out.println("batchImport  called");
        int successCount = 0;
        int errCount = 0;
        String errmsg = "";
        String originFileName = file.getOriginalFilename();
        Long size = file.getSize();
        XSSFWorkbook workbook = null;
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
            workbook = new XSSFWorkbook(inputStream);
            Sheet sheet = workbook.getSheetAt(0); // 获取第一个工作表
            //获取根单位
            QueryWrapper queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("dwname", "文卫采油厂");
            TjDw root = tjDwService.getOne(queryWrapper);
            root = tjDwService.getDwTreeById((long) root.getId());
            List<TjDw> dwList = new ArrayList<>();
            dwList = tjDwService.DwTreeToList(dwList, root);//所有单位列表
            List<TjGx> gxList = gxService.list();//所有干线列表
            int rowCount = sheet.getLastRowNum() - sheet.getFirstRowNum() + 1;
            for (int i = 1; i < rowCount; i++) {
                try {
                    Row row = sheet.getRow(i);
//            int columnCount = row.getLastCellNum() - row.getFirstCellNum();
//            for (int j = 0; j < columnCount; j++) {
//                Cell cell = row.getCell(j);
//                System.out.print(cell.toString() + "\t");
//            }
//            System.out.println();
                    Long dwL = null;
                    Long gxL = null;
                    String jh = row.getCell(0).toString().trim();
                    if (jh == null || jh.equals("")) {
//                System.out.println("+++++____________+");
                        continue;
                    }
                    String ip = row.getCell(1).toString().trim();
                    String dw = row.getCell(2).toString().trim();
                    String gx = row.getCell(3).toString().trim();
                    for (TjDw dwfor : dwList) {
                        System.out.println("danwei sql:" + dwfor + "    dw excel: " + dw);
                        if (dwfor.getDwname().equals(dw)) {
                            dwL = dwfor.getId();
                        }
                    }
                    for (TjGx gxfor : gxList) {
                        if (gxfor.getName().equals(gx)) {
                            gxL = gxfor.getId();
                        }
                    }
                    djxxService.save(new TDjxx(jh, ip, dwL, gxL));
                    successCount++;
                } catch (Exception e) {
                    errmsg += (i + 1) + ",";
                    errCount++;
                }
            }
            if (errCount > 0) {
                errmsg = errmsg.substring(0, errmsg.length() - 1);
                return R.error(60000, "导入出现错误！" + successCount + "行导入成功!    " +
                        errmsg + "行导入失败");
            } else {
                return R.success();
            }
        } catch (Exception e) {
            return R.error(60000, "导入失败！");
        } finally {
            if (workbook != null)
                workbook.close();
            inputStream.close();
        }
    }
}
